package com.qf.day4;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @date 2022/3/28
 * @desc
 */
@WebServlet("/context1")
public class ContextDemoServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //ServletContext   是 web 容器 启动的时候 创建的

        // 获取 ServletContext 对象 的方式
        ServletContext servletContext = this.getServletContext();

        ServletContext servletContext1 = req.getServletContext();

        ServletContext servletContext2 = req.getSession().getServletContext();

        ServletContext servletContext3 = this.getServletConfig().getServletContext();


        //System.out.println(servletContext);
        //System.out.println(servletContext1);
        //System.out.println(servletContext2);
        //System.out.println(servletContext3);

        //作用1
        String contextPath = servletContext.getContextPath();
        String contextPath1 = req.getContextPath();
        System.out.println(contextPath);
        System.out.println(contextPath1);//上下文路径（应用程序名称）



        // 作用2   读取全局的初始化参数

        String initParameter = servletContext.getInitParameter("charset");

        req.setCharacterEncoding(initParameter);
        System.out.println(initParameter);

        // 作用3  作为域对象使用   保存数据 或者 传递数据     是 全局共享的数据

        String name = req.getParameter("name");
        //req.setAttribute("name",name);

        servletContext.setAttribute("name",name);

        //转发
        //req.getRequestDispatcher("/main.jsp").forward(req,resp);

        //重定向
        resp.sendRedirect("/main.jsp");



    }
}
